<template>
  <div class="admin-product-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>产品管理</h2>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="产品名称">
          <el-input v-model="searchForm.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="类别">
          <el-select v-model="searchForm.category" placeholder="请选择类别" filterable @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="新鲜水果" value="新鲜水果" />
            <el-option label="绿色蔬菜" value="绿色蔬菜" />
            <el-option label="优质肉类" value="优质肉类" />
            <el-option label="新鲜海鲜" value="新鲜海鲜" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select v-model="searchForm.stock_status" placeholder="请选择库存状态" filterable @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="充足" value="sufficient" />
            <el-option label="低库存" value="low" />
            <el-option label="缺货" value="out_of_stock" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 产品列表 -->
      <el-table :data="products" style="width: 100%">
        <el-table-column prop="product_code" label="产品编号" width="120">
          <template #default="{ row }">
            {{ row.product_code || row.id || '无编号' }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="产品名称" width="150" />
        <el-table-column prop="category" label="类别" width="100">
          <template #default="{ row }">
            <el-tag>
              {{
                row.category_detail?.description?.replace(/类别$/, '') ||
                row.category?.name?.replace(/类别$/, '') ||
                (typeof row.category === 'string' ? row.category.replace(/类别$/, '') : '') ||
                '未知'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价" width="100">
          <template #default="{ row }">
            ¥{{ typeof row.price === 'number' ? row.price.toFixed(2) : Number(row.price || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100">
          <template #default="{ row }">
            {{ getStockQuantity(row) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock_status" label="库存状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStockStatusType(getCalculatedStockStatus(row))">
              {{ getStockStatusText(getCalculatedStockStatus(row)) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ row.created_at || row.created_time || '无日期' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link 
              size="small"
              :style="{ color: '#ffffff', backgroundColor: '#409EFF', padding: '2px 6px', borderRadius: '4px' }"
              @click="handleEdit(row)"
            >编辑</el-button>
            <el-button 
              type="success" 
              link 
              size="small"
              :style="{ color: '#ffffff', backgroundColor: '#67C23A', padding: '2px 6px', borderRadius: '4px' }"
              @click="handleViewDetails(row)"
            >查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新建产品' : '编辑产品'"
      width="50%"
    >
      <el-form :model="productForm" label-width="100px">
        <el-form-item label="产品名称">
          <el-input v-model="productForm.name" disabled />
        </el-form-item>
        <el-form-item label="类别">
          <el-select v-model="productForm.category" placeholder="请选择类别" filterable disabled>
            <el-option v-for="cat in categories" :key="cat.id" :label="cat.name" :value="cat.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="productForm.unit" disabled />
        </el-form-item>
        <el-form-item label="单价">
          <el-input-number v-model="productForm.price" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="成本价">
          <el-input-number v-model="productForm.cost_price" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input-number v-model="productForm.stock" :min="0" />
        </el-form-item>
        <el-form-item label="最低库存">
          <el-input-number v-model="productForm.min_stock" :min="0" />
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="productForm.supplier" disabled />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="productForm.description" type="textarea" />
        </el-form-item>
        <el-form-item label="过期预警天数">
          <el-input-number v-model="productForm.expiry_warning" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 产品详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="产品详情" width="500px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="产品名称">{{ detailProduct.name }}</el-descriptions-item>
        <el-descriptions-item label="类别">
          {{
            detailProduct.category_detail?.description?.replace(/类别$/, '') ||
            detailProduct.category?.name?.replace(/类别$/, '') ||
            (typeof detailProduct.category === 'string' ? detailProduct.category.replace(/类别$/, '') : '') ||
            '未知'
          }}
        </el-descriptions-item>
        <el-descriptions-item label="单价">¥{{ detailProduct.price }}</el-descriptions-item>
        <el-descriptions-item label="库存">{{ getStockQuantity(detailProduct) }}</el-descriptions-item>
        <el-descriptions-item label="供应商">{{ detailProduct.supplier }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ detailProduct.unit }}</el-descriptions-item>
        <el-descriptions-item label="最低库存">{{ detailProduct.min_stock }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ detailProduct.description }}</el-descriptions-item>
        <el-descriptions-item label="图片">
          <img v-if="detailProduct.image_url" :src="detailProduct.image_url" alt="产品图片" style="max-width: 100px; max-height: 100px;" />
          <span v-else>无</span>
        </el-descriptions-item>
        <el-descriptions-item label="过期预警天数">{{ detailProduct.expiry_warning }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailProduct.created_at || detailProduct.created_time || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'  // 改用 axios
import { getToken } from '@/utils/auth'  // 导入 getToken

// 搜索表单
const searchForm = ref({
  name: '',
  category: '',
  stock_status: '',
})

// 产品列表数据
const products = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('edit')
const productForm = ref({
  name: '',
  category: 'vegetables',
  unit: '',
  price: 0,
  cost_price: 0,
  stock: 0,
  min_stock: 0,
  supplier: '',
  description: '',
  expiry_warning: 3
})

// 产品详情弹窗
const detailDialogVisible = ref(false)
const detailProduct = ref({})

// 分类列表
const categories = ref([])

// 获取分类列表（带token）
const fetchCategories = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      categories.value = []
      return
    }
    const res = await axios.get('/api/categories/', {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    if (Array.isArray(res.data)) {
      categories.value = res.data
    } else if (res.data.data && Array.isArray(res.data.data)) {
      categories.value = res.data.data
    } else {
      categories.value = []
    }
  } catch (e) {
    categories.value = []
  }
}

const getCategoryName = (id) => {
  const found = categories.value.find(cat => cat.id === (id?.id || id))
  return found ? found.name : '未知'
}

// 获取类别文本
const getCategoryText = (category) => {
  if (!category) return '未知'
  // 如果是对象且有 category_detail
  if (typeof category === 'object' && category.category_detail) {
    const description = category.category_detail.description
    return description ? description.replace(/类别$/, '') : '未知'
  }
  // 如果有 category_detail 在父级
  if (category.id && category_detail) {
    const description = category_detail.description
    return description ? description.replace(/类别$/, '') : '未知'
  }
  return '未知'
}

// 获取库存状态样式
const getStockStatusType = (status) => {
  const typeMap = {
    sufficient: 'success',
    low: 'warning',
    out_of_stock: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取库存状态文本
const getStockStatusText = (status) => {
  const textMap = {
    sufficient: '充足',
    low: '低库存',
    out_of_stock: '缺货'
  }
  return textMap[status] || '未知'
}

// 获取库存数量
const getStockQuantity = (product) => {
  if (!product) return 0
  // 检查 stock_info 数组
  if (product.stock_info && Array.isArray(product.stock_info) && product.stock_info.length > 0) {
    // 获取第一个库存记录的 current_stock
    return Number(product.stock_info[0].current_stock) || 0
  }
  return 0
}

// 根据库存数量计算库存状态
const getCalculatedStockStatus = (product) => {
  const stock = getStockQuantity(product)
  const minStock = Number(product.min_stock || 10)
  
  if (stock <= 0) return 'out_of_stock'
  if (stock <= minStock) return 'low'
  return 'sufficient'
}

// 获取产品列表
const fetchProducts = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    // 获取所有商品数据
    const response = await axios.get('/api/products/', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    // 统一处理为数组
    let productsData = []
    if (Array.isArray(response.data)) {
      productsData = response.data
    } else if (response.data.results) {
      productsData = response.data.results
    } else if (response.data.items) {
      productsData = response.data.items
    }

    // 处理每个商品的数据
    const processedProducts = productsData.map(product => ({
      ...product,
      price: Number(product.price) || 0,
      cost_price: Number(product.cost_price) || 0,
      stock: getStockQuantity(product),
      min_stock: Number(product.min_stock) || 0,
      expiry_warning: Number(product.expiry_warning) || 3
    }))

    // 存储所有数据以便客户端过滤
    window.allProductsData = processedProducts
    filterProducts() // 初始显示全部
  } catch (error) {
    console.error('获取产品列表失败:', error.response?.data || error.message)
    ElMessage.error('获取产品列表失败: ' + (error.response?.data?.detail || error.message))
    products.value = []
    total.value = 0
  }
}

// 前端全量过滤函数
const filterProducts = () => {
  let filtered = window.allProductsData || [];

  // 名称模糊匹配
  if (searchForm.value.name) {
    const nameQuery = searchForm.value.name.toLowerCase().trim();
    filtered = filtered.filter(p => (p.name || '').toLowerCase().includes(nameQuery));
  }

  // 类别模糊包含匹配
  if (searchForm.value.category) {
    const categoryQuery = searchForm.value.category;
    filtered = filtered.filter(p => {
      let categoryText = '';
      if (p.category_detail && p.category_detail.description) {
        categoryText = p.category_detail.description;
      } else if (typeof p.category === 'object' && p.category.name) {
        categoryText = p.category.name;
      } else if (typeof p.category === 'string') {
        categoryText = p.category;
      }
      return categoryText.includes(categoryQuery);
    });
  }

  // 库存状态模糊匹配
  if (searchForm.value.stock_status) {
    const statusQuery = searchForm.value.stock_status.toLowerCase().trim();
    filtered = filtered.filter(p => {
      const status = getCalculatedStockStatus(p); // sufficient/low/out_of_stock
      return status.includes(statusQuery);
    });
  }

  // 描述模糊匹配（可选）
  if (searchForm.value.description) {
    const descQuery = searchForm.value.description.toLowerCase().trim();
    filtered = filtered.filter(p => (p.description || '').toLowerCase().includes(descQuery));
  }

  // 更新产品列表和分页
  total.value = filtered.length;
  // 分页
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  products.value = filtered.slice(start, end);
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  filterProducts();
}

// 处理重置
const handleReset = () => {
  searchForm.value = {
    name: '',
    category: '',
    stock_status: '',
  }
  currentPage.value = 1;
  filterProducts();
}

// 处理编辑
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  productForm.value = { ...row, category: row.category?.id || row.category || '' }
  await fetchCategories()
  dialogVisible.value = true
}

// 处理查看详情
const handleViewDetails = async (row) => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    const productId = row.id
    if (!productId) {
      ElMessage.warning('无法获取商品ID')
      return
    }

    const response = await axios.get(`/api/products/${productId}/`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    if (response.data) {
      detailProduct.value = response.data.data || response.data // 兼容两种格式
      detailDialogVisible.value = true
    } else {
      throw new Error('获取产品详情失败：响应数据为空')
    }
  } catch (error) {
    console.error('获取产品详情失败:', error.response?.data || error.message)
    ElMessage.error('获取产品详情失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 处理提交
const handleSubmit = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    const headers = {
      'Authorization': `Bearer ${token}`
    }

    const formData = {
      ...productForm.value,
      price: Number(productForm.value.price),
      cost_price: Number(productForm.value.cost_price),
      stock: Number(productForm.value.stock),
      min_stock: Number(productForm.value.min_stock),
      expiry_warning: Number(productForm.value.expiry_warning),
      category: Number(productForm.value.category) // 分类ID，确保为数字
    }

    // 前端必填校验
    if (!formData.name || !formData.category || !formData.unit || !formData.price) {
      ElMessage.error('请填写所有必填项');
      return;
    }

    const response = await axios.put(`/api/products/${formData.id}/`, formData, { headers })
    if (response.data) {
      ElMessage.success('更新产品成功')
    } else {
      throw new Error('更新产品失败：响应数据为空')
    }
    dialogVisible.value = false
    fetchProducts()
  } catch (error) {
    console.error('更新产品失败:', error.response?.data || error.message)
    ElMessage.error('更新产品失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  filterProducts();
}

const handleCurrentChange = (val) => {
  currentPage.value = val;
  filterProducts();
}

onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.admin-product-management {
  padding: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>